package com.aaa.project.zhreport.controller;

import com.aaa.common.utils.poi.ExcelUtil;
import com.aaa.framework.web.controller.BaseController;
import com.aaa.framework.web.domain.AjaxResult;
import com.aaa.framework.web.page.TableDataInfo;
import com.aaa.project.zhreport.controller.dto.YwfxDataTableAnnotationResDTO;
import com.aaa.project.zhreport.controller.dto.YwfxDataTemplateConfigReqDTO;
import com.aaa.project.zhreport.controller.dto.YwfxTempTableTemplateResDTO;
import com.aaa.project.zhreport.domain.YwfxDataTemplateConfig;
import com.aaa.project.zhreport.service.YwfxDataTemplateConfigService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author baibin
 * @version 1.0
 * @date 2025/4/8 9:57
 * @description YwfxDataTemplateConfigController
 */
@RestController
@RequestMapping("/data/template/cfg")
public class YwfxDataTemplateConfigController extends BaseController {

    @Resource
    private YwfxDataTemplateConfigService service;

    @GetMapping("/list")
    public TableDataInfo listPage(YwfxDataTemplateConfig query) {
        startPage();
        List<YwfxDataTemplateConfig> list = service.listPage(query);
        return getDataTable(list);
    }

    // 根据 ID 查询
    @GetMapping("/{id}")
    public AjaxResult findDetailById(@PathVariable Long id) {
        return success(service.findDetailById(id));
    }

    // 插入
    @PostMapping("/add")
    public AjaxResult add(@ModelAttribute YwfxDataTemplateConfigReqDTO request, HttpServletRequest httpRequest) {
        service.add(request, httpRequest);
        return success();
    }

    // 更新
    @PostMapping("/update")
    public AjaxResult update(@ModelAttribute YwfxDataTemplateConfigReqDTO request, HttpServletRequest httpRequest) {
        service.update(request, httpRequest);
        return success();
    }

    // 删除
    @DeleteMapping("/{id}")
    public AjaxResult deleteById(@PathVariable Long id) {
        service.deleteById(id);
        return success();
    }

    // 启用或禁用
    @PutMapping("/enable/{id}/{isEnable}")
    public AjaxResult enableOrDisable(@PathVariable Long id, @PathVariable String isEnable) {
        service.enableOrDisable(id, isEnable);
        return success();
    }

    @GetMapping("/list-all")
    public AjaxResult listAll(YwfxDataTemplateConfig query) {
        List<YwfxDataTemplateConfig> list = service.listPage(query);
        return success(list);
    }

    /**
     * 下载表对应中文注释模板
     *
     * @param response
     */
    @GetMapping("/download/filed/template")
    public void downloadTemplate(HttpServletResponse response) {
        try {
            // 文件名处理（URL编码）
            String filename = "表字段中文注释模板.txt";
            String encodedFilename = URLEncoder.encode(filename, String.valueOf(StandardCharsets.UTF_8));
            // 设置响应头
            response.setContentType("text/plain");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFilename + "\"");
            // 获取字段信息
            YwfxTempTableTemplateResDTO dto = new YwfxTempTableTemplateResDTO();
            Field[] fields = dto.getClass().getDeclaredFields();
            // 构建 txt 内容：第一行为字段名，第二行为示例数据
            StringBuilder sb = new StringBuilder();
            // 表头
            for (int i = 0; i < fields.length; i++) {
                if (i > 0) sb.append(",");
                sb.append(fields[i].getName());
            }
            sb.append("\n");
            // 示例数据（可替换为真实数据或留空）
            for (int i = 0; i < fields.length; i++) {
                if (i > 0) sb.append(",");
                sb.append("1");
            }
            // 输出到客户端
            try (OutputStream os = response.getOutputStream()) {
                os.write(sb.toString().getBytes(StandardCharsets.UTF_8));
                os.flush();
            }
        } catch (IOException e) {
            throw new RuntimeException("导出txt文件失败", e);
        }
    }

    @GetMapping("/download/{id}/{type}")
    public void download(@PathVariable Long id, @PathVariable Integer type, HttpServletResponse response) {
        service.download(id, type, response);
    }

    /**
     * 下载临时表数据模板
     *
     * @param response
     */
    @GetMapping("/temp/table/download")
    public void downloadTempTableTemplate(HttpServletResponse response) {
        try {
            // 文件名处理（URL编码）
            String filename = "临时表导入模板.txt";
            String encodedFilename = URLEncoder.encode(filename, String.valueOf(StandardCharsets.UTF_8));
            // 设置响应头
            response.setContentType("text/plain");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFilename + "\"");
            // 获取字段信息
            YwfxTempTableTemplateResDTO dto = new YwfxTempTableTemplateResDTO();
            Field[] fields = dto.getClass().getDeclaredFields();
            // 构建 txt 内容：第一行为字段名，第二行为示例数据
            StringBuilder sb = new StringBuilder();
            // 表头
            for (int i = 0; i < fields.length; i++) {
                if (i > 0) sb.append(",");
                sb.append(fields[i].getName());
            }
            sb.append("\n");
            // 示例数据（可替换为真实数据或留空）
            for (int i = 0; i < fields.length; i++) {
                if (i > 0) sb.append(",");
                sb.append("1");
            }
            // 输出到客户端
            try (OutputStream os = response.getOutputStream()) {
                os.write(sb.toString().getBytes(StandardCharsets.UTF_8));
                os.flush();
            }
        } catch (IOException e) {
            throw new RuntimeException("导出txt文件失败", e);
        }
    }
}
